home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 1998 November / IRIX 6.5.2 Base Documentation November 1998.img / usr / share / catman / u_man / cat1 / perldsc.z / perldsc
Text File  |  1998-10-30  |  38KB  |  1,189 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perldsc - Perl Data Structures Cookbook
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      The single feature most sorely lacking in the Perl programming language
  13.      prior to its 5.0 release was complex data structures.  Even without
  14.      direct language support, some valiant programmers did manage to emulate
  15.      them, but it was hard work and not for the faint of heart.  You could
  16.      occasionally get away with the $m{$LoL,$b} notation borrowed from _a_w_k in
  17.      which the keys are actually more like a single concatenated string
  18.      "$LoL$b", but traversal and sorting were difficult.  More desperate
  19.      programmers even hacked Perl's internal symbol table directly, a strategy
  20.      that proved hard to develop and maintain--to put it mildly.
  21.  
  22.      The 5.0 release of Perl let us have complex data structures.  You may now
  23.      write something like this and all of a sudden, you'd have a array with
  24.      three dimensions!
  25.  
  26.          for $x (1 .. 10) {
  27.              for $y (1 .. 10) {
  28.                  for $z (1 .. 10) {
  29.                      $LoL[$x][$y][$z] =
  30.                          $x ** $y + $z;
  31.                  }
  32.              }
  33.          }
  34.  
  35.      Alas, however simple this may appear, underneath it's a much more
  36.      elaborate construct than meets the eye!
  37.  
  38.      How do you print it out?  Why can't you say just print @LoL?  How do you
  39.      sort it?  How can you pass it to a function or get one of these back from
  40.      a function?  Is is an object?  Can you save it to disk to read back
  41.      later?  How do you access whole rows or columns of that matrix?  Do all
  42.      the values have to be numeric?
  43.  
  44.      As you see, it's quite easy to become confused.  While some small portion
  45.      of the blame for this can be attributed to the reference-based
  46.      implementation, it's really more due to a lack of existing documentation
  47.      with examples designed for the beginner.
  48.  
  49.      This document is meant to be a detailed but understandable treatment of
  50.      the many different sorts of data structures you might want to develop.
  51.      It should also serve as a cookbook of examples.  That way, when you need
  52.      to create one of these complex data structures, you can just pinch,
  53.      pilfer, or purloin a drop-in example from here.
  54.  
  55.      Let's look at each of these possible constructs in detail.  There are
  56.      separate sections on each of the following:
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  71.  
  72.  
  73.  
  74.      +o arrays of arrays
  75.  
  76.      +o hashes of arrays
  77.  
  78.      +o arrays of hashes
  79.  
  80.      +o hashes of hashes
  81.  
  82.      +o more elaborate constructs
  83.  
  84.      But for now, let's look at some of the general issues common to all of
  85.      these types of data structures.
  86.  
  87. RRRREEEEFFFFEEEERRRREEEENNNNCCCCEEEESSSS
  88.      The most important thing to understand about all data structures in Perl
  89.      -- including multidimensional arrays--is that even though they might
  90.      appear otherwise, Perl @ARRAYs and %HASHes are all internally one-
  91.      dimensional.  They can hold only scalar values (meaning a string, number,
  92.      or a reference).  They cannot directly contain other arrays or hashes,
  93.      but instead contain _r_e_f_e_r_e_n_c_e_s to other arrays or hashes.
  94.  
  95.      You can't use a reference to a array or hash in quite the same way that
  96.      you would a real array or hash.  For C or C++ programmers unused to
  97.      distinguishing between arrays and pointers to the same, this can be
  98.      confusing.  If so, just think of it as the difference between a structure
  99.      and a pointer to a structure.
  100.  
  101.      You can (and should) read more about references in the _p_e_r_l_r_e_f(1) man
  102.      page.  Briefly, references are rather like pointers that know what they
  103.      point to.  (Objects are also a kind of reference, but we won't be needing
  104.      them right away--if ever.)  This means that when you have something which
  105.      looks to you like an access to a two-or-more-dimensional array and/or
  106.      hash, what's really going on is that the base type is merely a one-
  107.      dimensional entity that contains references to the next level.  It's just
  108.      that you can _u_s_e it as though it were a two-dimensional one.  This is
  109.      actually the way almost all C multidimensional arrays work as well.
  110.  
  111.          $list[7][12]                        # array of arrays
  112.          $list[7]{string}                    # array of hashes
  113.          $hash{string}[7]                    # hash of arrays
  114.          $hash{string}{'another string'}     # hash of hashes
  115.  
  116.      Now, because the top level contains only references, if you try to print
  117.      out your array in with a simple _p_r_i_n_t() function, you'll get something
  118.      that doesn't look very nice, like this:
  119.  
  120.          @LoL = ( [2, 3], [4, 5, 7], [0] );
  121.          print $LoL[1][2];
  122.        7
  123.          print @LoL;
  124.        ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)
  125.  
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  137.  
  138.  
  139.  
  140.      That's because Perl doesn't (ever) implicitly dereference your variables.
  141.      If you want to get at the thing a reference is referring to, then you
  142.      have to do this yourself using either prefix typing indicators, like
  143.      ${$blah}, @{$blah}, @{$blah[$i]}, or else postfix pointer arrows, like
  144.      $a->[3], $h->{fred}, or even $ob->_m_e_t_h_o_d()->[3].
  145.  
  146. CCCCOOOOMMMMMMMMOOOONNNN MMMMIIIISSSSTTTTAAAAKKKKEEEESSSS
  147.      The two most common mistakes made in constructing something like an array
  148.      of arrays is either accidentally counting the number of elements or else
  149.      taking a reference to the same memory location repeatedly.  Here's the
  150.      case where you just get the count instead of a nested array:
  151.  
  152.          for $i (1..10) {
  153.              @list = somefunc($i);
  154.              $LoL[$i] = @list;       # WRONG!
  155.          }
  156.  
  157.      That's just the simple case of assigning a list to a scalar and getting
  158.      its element count.  If that's what you really and truly want, then you
  159.      might do well to consider being a tad more explicit about it, like this:
  160.  
  161.          for $i (1..10) {
  162.              @list = somefunc($i);
  163.              $counts[$i] = scalar @list;
  164.          }
  165.  
  166.      Here's the case of taking a reference to the same memory location again
  167.      and again:
  168.  
  169.          for $i (1..10) {
  170.              @list = somefunc($i);
  171.              $LoL[$i] = \@list;      # WRONG!
  172.          }
  173.  
  174.      So, what's the big problem with that?  It looks right, doesn't it?  After
  175.      all, I just told you that you need an array of references, so by golly,
  176.      you've made me one!
  177.  
  178.      Unfortunately, while this is true, it's still broken.  All the references
  179.      in @LoL refer to the _v_e_r_y _s_a_m_e _p_l_a_c_e, and they will therefore all hold
  180.      whatever was last in @list!  It's similar to the problem demonstrated in
  181.      the following C program:
  182.  
  183.          #include <pwd.h>
  184.          main() {
  185.              struct passwd *getpwnam(), *rp, *dp;
  186.              rp = getpwnam("root");
  187.              dp = getpwnam("daemon");
  188.  
  189.              printf("daemon name is %s\nroot name is %s\n",
  190.                      dp->pw_name, rp->pw_name);
  191.          }
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  203.  
  204.  
  205.  
  206.      Which will print
  207.  
  208.          daemon name is daemon
  209.          root name is daemon
  210.  
  211.      The problem is that both rp and dp are pointers to the same location in
  212.      memory!  In C, you'd have to remember to _m_a_l_l_o_c() yourself some new
  213.      memory.  In Perl, you'll want to use the array constructor [] or the hash
  214.      constructor {} instead.   Here's the right way to do the preceding broken
  215.      code fragments:
  216.  
  217.          for $i (1..10) {
  218.              @list = somefunc($i);
  219.              $LoL[$i] = [ @list ];
  220.          }
  221.  
  222.      The square brackets make a reference to a new array with a _c_o_p_y of what's
  223.      in @list at the time of the assignment.  This is what you want.
  224.  
  225.      Note that this will produce something similar, but it's much harder to
  226.      read:
  227.  
  228.          for $i (1..10) {
  229.              @list = 0 .. $i;
  230.              @{$LoL[$i]} = @list;
  231.          }
  232.  
  233.      Is it the same?  Well, maybe so--and maybe not.  The subtle difference is
  234.      that when you assign something in square brackets, you know for sure it's
  235.      always a brand new reference with a new _c_o_p_y of the data.  Something else
  236.      could be going on in this new case with the @{$LoL[$i]}} dereference on
  237.      the left-hand-side of the assignment.  It all depends on whether $LoL[$i]
  238.      had been undefined to start with, or whether it already contained a
  239.      reference.  If you had already populated @LoL with references, as in
  240.  
  241.          $LoL[3] = \@another_list;
  242.  
  243.      Then the assignment with the indirection on the left-hand-side would use
  244.      the existing reference that was already there:
  245.  
  246.          @{$LoL[3]} = @list;
  247.  
  248.      Of course, this _w_o_u_l_d have the "interesting" effect of clobbering
  249.      @another_list.  (Have you ever noticed how when a programmer says
  250.      something is "interesting", that rather than meaning "intriguing",
  251.      they're disturbingly more apt to mean that it's "annoying", "difficult",
  252.      or both?  :-)
  253.  
  254.      So just remember always to use the array or hash constructors with [] or
  255.      {}, and you'll be fine, although it's not always optimally efficient.
  256.  
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  269.  
  270.  
  271.  
  272.      Surprisingly, the following dangerous-looking construct will actually
  273.      work out fine:
  274.  
  275.          for $i (1..10) {
  276.              my @list = somefunc($i);
  277.              $LoL[$i] = \@list;
  278.          }
  279.  
  280.      That's because _m_y() is more of a run-time statement than it is a
  281.      compile-time declaration _p_e_r _s_e.  This means that the _m_y() variable is
  282.      remade afresh each time through the loop.  So even though it _l_o_o_k_s as
  283.      though you stored the same variable reference each time, you actually did
  284.      not!  This is a subtle distinction that can produce more efficient code
  285.      at the risk of misleading all but the most experienced of programmers.
  286.      So I usually advise against teaching it to beginners.  In fact, except
  287.      for passing arguments to functions, I seldom like to see the gimme-a-
  288.      reference operator (backslash) used much at all in code.  Instead, I
  289.      advise beginners that they (and most of the rest of us) should try to use
  290.      the much more easily understood constructors [] and {} instead of relying
  291.      upon lexical (or dynamic) scoping and hidden reference-counting to do the
  292.      right thing behind the scenes.
  293.  
  294.      In summary:
  295.  
  296.          $LoL[$i] = [ @list ];       # usually best
  297.          $LoL[$i] = \@list;          # perilous; just how my() was that list?
  298.          @{ $LoL[$i] } = @list;      # way too tricky for most programmers
  299.  
  300.  
  301. CCCCAAAAVVVVEEEEAAAATTTT OOOONNNN PPPPRRRREEEECCCCEEEEDDDDEEEENNNNCCCCEEEE
  302.      Speaking of things like @{$LoL[$i]}, the following are actually the same
  303.      thing:
  304.  
  305.          $listref->[2][2]    # clear
  306.          $$listref[2][2]     # confusing
  307.  
  308.      That's because Perl's precedence rules on its five prefix dereferencers
  309.      (which look like someone swearing: $ @ * % &) make them bind more tightly
  310.      than the postfix subscripting brackets or braces!  This will no doubt
  311.      come as a great shock to the C or C++ programmer, who is quite accustomed
  312.      to using *a[i] to mean what's pointed to by the _i'_t_h element of a.  That
  313.      is, they first take the subscript, and only then dereference the thing at
  314.      that subscript.  That's fine in C, but this isn't C.
  315.  
  316.      The seemingly equivalent construct in Perl, $$listref[$i] first does the
  317.      deref of $listref, making it take $listref as a reference to an array,
  318.      and then dereference that, and finally tell you the _i'_t_h value of the
  319.      array pointed to by $LoL. If you wanted the C notion, you'd have to write
  320.      ${$LoL[$i]} to force the $LoL[$i] to get evaluated first before the
  321.      leading $ dereferencer.
  322.  
  323.  
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  335.  
  336.  
  337.  
  338. WWWWHHHHYYYY YYYYOOOOUUUU SSSSHHHHOOOOUUUULLLLDDDD AAAALLLLWWWWAAAAYYYYSSSS uuuusssseeee ssssttttrrrriiiicccctttt
  339.      If this is starting to sound scarier than it's worth, relax.  Perl has
  340.      some features to help you avoid its most common pitfalls.  The best way
  341.      to avoid getting confused is to start every program like this:
  342.  
  343.          #!/usr/bin/perl -w
  344.          use strict;
  345.  
  346.      This way, you'll be forced to declare all your variables with _m_y() and
  347.      also disallow accidental "symbolic dereferencing".  Therefore if you'd
  348.      done this:
  349.  
  350.          my $listref = [
  351.              [ "fred", "barney", "pebbles", "bambam", "dino", ],
  352.              [ "homer", "bart", "marge", "maggie", ],
  353.              [ "george", "jane", "elroy", "judy", ],
  354.          ];
  355.  
  356.          print $listref[2][2];
  357.  
  358.      The compiler would immediately flag that as an error _a_t _c_o_m_p_i_l_e _t_i_m_e,
  359.      because you were accidentally accessing @listref, an undeclared variable,
  360.      and it would thereby remind you to write instead:
  361.  
  362.          print $listref->[2][2]
  363.  
  364.  
  365. DDDDEEEEBBBBUUUUGGGGGGGGIIIINNNNGGGG
  366.      Before version 5.002, the standard Perl debugger didn't do a very nice
  367.      job of printing out complex data structures.  With 5.002 or above, the
  368.      debugger includes several new features, including command line editing as
  369.      well as the x command to dump out complex data structures.  For example,
  370.      given the assignment to $LoL above, here's the debugger output:
  371.  
  372.          DB<1> X $LoL
  373.          $LoL = ARRAY(0x13b5a0)
  374.             0  ARRAY(0x1f0a24)
  375.                0  'fred'
  376.                1  'barney'
  377.                2  'pebbles'
  378.                3  'bambam'
  379.                4  'dino'
  380.             1  ARRAY(0x13b558)
  381.                0  'homer'
  382.                1  'bart'
  383.                2  'marge'
  384.                3  'maggie'
  385.             2  ARRAY(0x13b540)
  386.                0  'george'
  387.                1  'jane'
  388.                2  'elroy'
  389.                3  'judy'
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  401.  
  402.  
  403.  
  404.      There's also a lowercase xxxx command which is nearly the same.
  405.  
  406. CCCCOOOODDDDEEEE EEEEXXXXAAAAMMMMPPPPLLLLEEEESSSS
  407.      Presented with little comment (these will get their own manpages someday)
  408.      here are short code examples illustrating access of various types of data
  409.      structures.
  410.  
  411. LLLLIIIISSSSTTTTSSSS OOOOFFFF LLLLIIIISSSSTTTTSSSS
  412.      DDDDeeeeccccllllaaaarrrraaaattttiiiioooonnnn ooooffff aaaa LLLLIIIISSSSTTTT OOOOFFFF LLLLIIIISSSSTTTTSSSS
  413.  
  414.       @LoL = (
  415.              [ "fred", "barney" ],
  416.              [ "george", "jane", "elroy" ],
  417.              [ "homer", "marge", "bart" ],
  418.            );
  419.  
  420.  
  421.      GGGGeeeennnneeeerrrraaaattttiiiioooonnnn ooooffff aaaa LLLLIIIISSSSTTTT OOOOFFFF LLLLIIIISSSSTTTTSSSS
  422.  
  423.       # reading from file
  424.       while ( <> ) {
  425.           push @LoL, [ split ];
  426.       }
  427.  
  428.       # calling a function
  429.       for $i ( 1 .. 10 ) {
  430.           $LoL[$i] = [ somefunc($i) ];
  431.       }
  432.  
  433.       # using temp vars
  434.       for $i ( 1 .. 10 ) {
  435.           @tmp = somefunc($i);
  436.           $LoL[$i] = [ @tmp ];
  437.       }
  438.  
  439.       # add to an existing row
  440.       push @{ $LoL[0] }, "wilma", "betty";
  441.  
  442.  
  443.      AAAAcccccccceeeessssssss aaaannnndddd PPPPrrrriiiinnnnttttiiiinnnngggg ooooffff aaaa LLLLIIIISSSSTTTT OOOOFFFF LLLLIIIISSSSTTTTSSSS
  444.  
  445.       # one element
  446.       $LoL[0][0] = "Fred";
  447.  
  448.       # another element
  449.       $LoL[1][1] =~ s/(\w)/\u$1/;
  450.  
  451.       # print the whole thing with refs
  452.       for $aref ( @LoL ) {
  453.           print "\t [ @$aref ],\n";
  454.       }
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  467.  
  468.  
  469.  
  470.       # print the whole thing with indices
  471.       for $i ( 0 .. $#LoL ) {
  472.           print "\t [ @{$LoL[$i]} ],\n";
  473.       }
  474.  
  475.       # print the whole thing one at a time
  476.       for $i ( 0 .. $#LoL ) {
  477.           for $j ( 0 .. $#{ $LoL[$i] } ) {
  478.               print "elt $i $j is $LoL[$i][$j]\n";
  479.           }
  480.       }
  481.  
  482.  
  483. HHHHAAAASSSSHHHHEEEESSSS OOOOFFFF LLLLIIIISSSSTTTTSSSS
  484.      DDDDeeeeccccllllaaaarrrraaaattttiiiioooonnnn ooooffff aaaa HHHHAAAASSSSHHHH OOOOFFFF LLLLIIIISSSSTTTTSSSS
  485.  
  486.       %HoL = (
  487.              flintstones        => [ "fred", "barney" ],
  488.              jetsons            => [ "george", "jane", "elroy" ],
  489.              simpsons           => [ "homer", "marge", "bart" ],
  490.            );
  491.  
  492.  
  493.      GGGGeeeennnneeeerrrraaaattttiiiioooonnnn ooooffff aaaa HHHHAAAASSSSHHHH OOOOFFFF LLLLIIIISSSSTTTTSSSS
  494.  
  495.       # reading from file
  496.       # flintstones: fred barney wilma dino
  497.       while ( <> ) {
  498.           next unless s/^(.*?):\s*//;
  499.           $HoL{$1} = [ split ];
  500.       }
  501.  
  502.       # reading from file; more temps
  503.       # flintstones: fred barney wilma dino
  504.       while ( $line = <> ) {
  505.           ($who, $rest) = split /:\s*/, $line, 2;
  506.           @fields = split ' ', $rest;
  507.           $HoL{$who} = [ @fields ];
  508.       }
  509.  
  510.       # calling a function that returns a list
  511.       for $group ( "simpsons", "jetsons", "flintstones" ) {
  512.           $HoL{$group} = [ get_family($group) ];
  513.       }
  514.  
  515.       # likewise, but using temps
  516.       for $group ( "simpsons", "jetsons", "flintstones" ) {
  517.           @members = get_family($group);
  518.           $HoL{$group} = [ @members ];
  519.       }
  520.  
  521.  
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  533.  
  534.  
  535.  
  536.       # append new members to an existing family
  537.       push @{ $HoL{"flintstones"} }, "wilma", "betty";
  538.  
  539.  
  540.      AAAAcccccccceeeessssssss aaaannnndddd PPPPrrrriiiinnnnttttiiiinnnngggg ooooffff aaaa HHHHAAAASSSSHHHH OOOOFFFF LLLLIIIISSSSTTTTSSSS
  541.  
  542.       # one element
  543.       $HoL{flintstones}[0] = "Fred";
  544.  
  545.       # another element
  546.       $HoL{simpsons}[1] =~ s/(\w)/\u$1/;
  547.  
  548.       # print the whole thing
  549.       foreach $family ( keys %HoL ) {
  550.           print "$family: @{ $HoL{$family} }\n"
  551.       }
  552.  
  553.       # print the whole thing with indices
  554.       foreach $family ( keys %HoL ) {
  555.           print "family: ";
  556.           foreach $i ( 0 .. $#{ $HoL{$family} } ) {
  557.               print " $i = $HoL{$family}[$i]";
  558.           }
  559.           print "\n";
  560.       }
  561.  
  562.       # print the whole thing sorted by number of members
  563.       foreach $family ( sort { @{$HoL{$b}} <=> @{$HoL{$a}} } keys %HoL ) {
  564.           print "$family: @{ $HoL{$family} }\n"
  565.       }
  566.  
  567.       # print the whole thing sorted by number of members and name
  568.       foreach $family ( sort {
  569.                                  @{$HoL{$b}} <=> @{$HoL{$a}}
  570.                                              ||
  571.                                          $a cmp $b
  572.                  } keys %HoL )
  573.       {
  574.           print "$family: ", join(", ", sort @{ $HoL{$family}), "\n";
  575.       }
  576.  
  577.  
  578. LLLLIIIISSSSTTTTSSSS OOOOFFFF HHHHAAAASSSSHHHHEEEESSSS
  579.      DDDDeeeeccccllllaaaarrrraaaattttiiiioooonnnn ooooffff aaaa LLLLIIIISSSSTTTT OOOOFFFF HHHHAAAASSSSHHHHEEEESSSS
  580.  
  581.  
  582.  
  583.  
  584.  
  585.  
  586.  
  587.  
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  599.  
  600.  
  601.  
  602.       @LoH = (
  603.              {
  604.                  Lead     => "fred",
  605.                  Friend   => "barney",
  606.              },
  607.              {
  608.                  Lead     => "george",
  609.                  Wife     => "jane",
  610.                  Son      => "elroy",
  611.              },
  612.              {
  613.                  Lead     => "homer",
  614.                  Wife     => "marge",
  615.                  Son      => "bart",
  616.              }
  617.        );
  618.  
  619.  
  620.      GGGGeeeennnneeeerrrraaaattttiiiioooonnnn ooooffff aaaa LLLLIIIISSSSTTTT OOOOFFFF HHHHAAAASSSSHHHHEEEESSSS
  621.  
  622.       # reading from file
  623.       # format: LEAD=fred FRIEND=barney
  624.       while ( <> ) {
  625.           $rec = {};
  626.           for $field ( split ) {
  627.               ($key, $value) = split /=/, $field;
  628.               $rec->{$key} = $value;
  629.           }
  630.           push @LoH, $rec;
  631.       }
  632.  
  633.       # reading from file
  634.       # format: LEAD=fred FRIEND=barney
  635.       # no temp
  636.       while ( <> ) {
  637.           push @LoH, { split /[\s+=]/ };
  638.       }
  639.  
  640.       # calling a function  that returns a key,value list, like
  641.       # "lead","fred","daughter","pebbles"
  642.       while ( %fields = getnextpairset() ) {
  643.           push @LoH, { %fields };
  644.       }
  645.  
  646.       # likewise, but using no temp vars
  647.       while (<>) {
  648.           push @LoH, { parsepairs($_) };
  649.       }
  650.  
  651.       # add key/value to an element
  652.       $LoH[0]{pet} = "dino";
  653.       $LoH[2]{pet} = "santa's little helper";
  654.  
  655.  
  656.  
  657.                                                                        PPPPaaaaggggeeee 11110000
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  665.  
  666.  
  667.  
  668.      AAAAcccccccceeeessssssss aaaannnndddd PPPPrrrriiiinnnnttttiiiinnnngggg ooooffff aaaa LLLLIIIISSSSTTTT OOOOFFFF HHHHAAAASSSSHHHHEEEESSSS
  669.  
  670.       # one element
  671.       $LoH[0]{lead} = "fred";
  672.  
  673.       # another element
  674.       $LoH[1]{lead} =~ s/(\w)/\u$1/;
  675.  
  676.       # print the whole thing with refs
  677.       for $href ( @LoH ) {
  678.           print "{ ";
  679.           for $role ( keys %$href ) {
  680.               print "$role=$href->{$role} ";
  681.           }
  682.           print "}\n";
  683.       }
  684.  
  685.       # print the whole thing with indices
  686.       for $i ( 0 .. $#LoH ) {
  687.           print "$i is { ";
  688.           for $role ( keys %{ $LoH[$i] } ) {
  689.               print "$role=$LoH[$i]{$role} ";
  690.           }
  691.           print "}\n";
  692.       }
  693.  
  694.       # print the whole thing one at a time
  695.       for $i ( 0 .. $#LoH ) {
  696.           for $role ( keys %{ $LoH[$i] } ) {
  697.               print "elt $i $role is $LoH[$i]{$role}\n";
  698.           }
  699.       }
  700.  
  701.  
  702. HHHHAAAASSSSHHHHEEEESSSS OOOOFFFF HHHHAAAASSSSHHHHEEEESSSS
  703.      DDDDeeeeccccllllaaaarrrraaaattttiiiioooonnnn ooooffff aaaa HHHHAAAASSSSHHHH OOOOFFFF HHHHAAAASSSSHHHHEEEESSSS
  704.  
  705.  
  706.  
  707.  
  708.  
  709.  
  710.  
  711.  
  712.  
  713.  
  714.  
  715.  
  716.  
  717.  
  718.  
  719.  
  720.  
  721.  
  722.  
  723.                                                                        PPPPaaaaggggeeee 11111111
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  731.  
  732.  
  733.  
  734.       %HoH = (
  735.              flintstones => {
  736.                      lead      => "fred",
  737.                      pal       => "barney",
  738.              },
  739.              jetsons     => {
  740.                      lead      => "george",
  741.                      wife      => "jane",
  742.                      "his boy" => "elroy",
  743.              },
  744.              simpsons    => {
  745.                      lead      => "homer",
  746.                      wife      => "marge",
  747.                      kid       => "bart",
  748.              },
  749.       );
  750.  
  751.  
  752.      GGGGeeeennnneeeerrrraaaattttiiiioooonnnn ooooffff aaaa HHHHAAAASSSSHHHH OOOOFFFF HHHHAAAASSSSHHHHEEEESSSS
  753.  
  754.       # reading from file
  755.       # flintstones: lead=fred pal=barney wife=wilma pet=dino
  756.       while ( <> ) {
  757.           next unless s/^(.*?):\s*//;
  758.           $who = $1;
  759.           for $field ( split ) {
  760.               ($key, $value) = split /=/, $field;
  761.               $HoH{$who}{$key} = $value;
  762.           }
  763.  
  764.       # reading from file; more temps
  765.       while ( <> ) {
  766.           next unless s/^(.*?):\s*//;
  767.           $who = $1;
  768.           $rec = {};
  769.           $HoH{$who} = $rec;
  770.           for $field ( split ) {
  771.               ($key, $value) = split /=/, $field;
  772.               $rec->{$key} = $value;
  773.           }
  774.       }
  775.  
  776.       # calling a function  that returns a key,value hash
  777.       for $group ( "simpsons", "jetsons", "flintstones" ) {
  778.           $HoH{$group} = { get_family($group) };
  779.       }
  780.  
  781.       # likewise, but using temps
  782.       for $group ( "simpsons", "jetsons", "flintstones" ) {
  783.           %members = get_family($group);
  784.           $HoH{$group} = { %members };
  785.       }
  786.  
  787.  
  788.  
  789.                                                                        PPPPaaaaggggeeee 11112222
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  797.  
  798.  
  799.  
  800.       # append new members to an existing family
  801.       %new_folks = (
  802.           wife => "wilma",
  803.           pet  => "dino";
  804.       );
  805.  
  806.       for $what (keys %new_folks) {
  807.           $HoH{flintstones}{$what} = $new_folks{$what};
  808.       }
  809.  
  810.  
  811.      AAAAcccccccceeeessssssss aaaannnndddd PPPPrrrriiiinnnnttttiiiinnnngggg ooooffff aaaa HHHHAAAASSSSHHHH OOOOFFFF HHHHAAAASSSSHHHHEEEESSSS
  812.  
  813.       # one element
  814.       $HoH{flintstones}{wife} = "wilma";
  815.  
  816.       # another element
  817.       $HoH{simpsons}{lead} =~ s/(\w)/\u$1/;
  818.  
  819.       # print the whole thing
  820.       foreach $family ( keys %HoH ) {
  821.           print "$family: { ";
  822.           for $role ( keys %{ $HoH{$family} } ) {
  823.               print "$role=$HoH{$family}{$role} ";
  824.           }
  825.           print "}\n";
  826.       }
  827.  
  828.       # print the whole thing  somewhat sorted
  829.       foreach $family ( sort keys %HoH ) {
  830.           print "$family: { ";
  831.           for $role ( sort keys %{ $HoH{$family} } ) {
  832.               print "$role=$HoH{$family}{$role} ";
  833.           }
  834.           print "}\n";
  835.       }
  836.  
  837.       # print the whole thing sorted by number of members
  838.       foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$a}} } keys %HoH ) {
  839.           print "$family: { ";
  840.           for $role ( sort keys %{ $HoH{$family} } ) {
  841.               print "$role=$HoH{$family}{$role} ";
  842.           }
  843.           print "}\n";
  844.       }
  845.  
  846.       # establish a sort order (rank) for each role
  847.       $i = 0;
  848.       for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i }
  849.  
  850.  
  851.  
  852.  
  853.  
  854.  
  855.                                                                        PPPPaaaaggggeeee 11113333
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  863.  
  864.  
  865.  
  866.       # now print the whole thing sorted by number of members
  867.       foreach $family ( sort { keys %{ $HoH{$b} } <=> keys %{ $HoH{$a} } } keys %HoH ) {
  868.           print "$family: { ";
  869.           # and print these according to rank order
  870.           for $role ( sort { $rank{$a} <=> $rank{$b} }  keys %{ $HoH{$family} } ) {
  871.               print "$role=$HoH{$family}{$role} ";
  872.           }
  873.           print "}\n";
  874.       }
  875.  
  876.  
  877. MMMMOOOORRRREEEE EEEELLLLAAAABBBBOOOORRRRAAAATTTTEEEE RRRREEEECCCCOOOORRRRDDDDSSSS
  878.      DDDDeeeeccccllllaaaarrrraaaattttiiiioooonnnn ooooffff MMMMOOOORRRREEEE EEEELLLLAAAABBBBOOOORRRRAAAATTTTEEEE RRRREEEECCCCOOOORRRRDDDDSSSS
  879.  
  880.      Here's a sample showing how to create and use a record whose fields are
  881.      of many different sorts:
  882.  
  883.           $rec = {
  884.               TEXT      => $string,
  885.               SEQUENCE  => [ @old_values ],
  886.               LOOKUP    => { %some_table },
  887.               THATCODE  => \&some_function,
  888.               THISCODE  => sub { $_[0] ** $_[1] },
  889.               HANDLE    => \*STDOUT,
  890.           };
  891.  
  892.           print $rec->{TEXT};
  893.  
  894.           print $rec->{LIST}[0];
  895.           $last = pop @ { $rec->{SEQUENCE} };
  896.  
  897.           print $rec->{LOOKUP}{"key"};
  898.           ($first_k, $first_v) = each %{ $rec->{LOOKUP} };
  899.  
  900.           $answer = $rec->{THATCODE}->($arg);
  901.           $answer = $rec->{THISCODE}->($arg1, $arg2);
  902.  
  903.           # careful of extra block braces on fh ref
  904.           print { $rec->{HANDLE} } "a string\n";
  905.  
  906.           use FileHandle;
  907.           $rec->{HANDLE}->autoflush(1);
  908.           $rec->{HANDLE}->print(" a string\n");
  909.  
  910.  
  911.      DDDDeeeeccccllllaaaarrrraaaattttiiiioooonnnn ooooffff aaaa HHHHAAAASSSSHHHH OOOOFFFF CCCCOOOOMMMMPPPPLLLLEEEEXXXX RRRREEEECCCCOOOORRRRDDDDSSSS
  912.  
  913.  
  914.  
  915.  
  916.  
  917.  
  918.  
  919.  
  920.  
  921.                                                                        PPPPaaaaggggeeee 11114444
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  929.  
  930.  
  931.  
  932.           %TV = (
  933.              flintstones => {
  934.                  series   => "flintstones",
  935.                  nights   => [ qw(monday thursday friday) ],
  936.                  members  => [
  937.                      { name => "fred",    role => "lead", age  => 36, },
  938.                      { name => "wilma",   role => "wife", age  => 31, },
  939.                      { name => "pebbles", role => "kid",  age  =>  4, },
  940.                  ],
  941.              },
  942.  
  943.              jetsons     => {
  944.                  series   => "jetsons",
  945.                  nights   => [ qw(wednesday saturday) ],
  946.                  members  => [
  947.                      { name => "george",  role => "lead", age  => 41, },
  948.                      { name => "jane",    role => "wife", age  => 39, },
  949.                      { name => "elroy",   role => "kid",  age  =>  9, },
  950.                  ],
  951.               },
  952.  
  953.              simpsons    => {
  954.                  series   => "simpsons",
  955.                  nights   => [ qw(monday) ],
  956.                  members  => [
  957.                      { name => "homer", role => "lead", age  => 34, },
  958.                      { name => "marge", role => "wife", age => 37, },
  959.                      { name => "bart",  role => "kid",  age  =>  11, },
  960.                  ],
  961.               },
  962.            );
  963.  
  964.  
  965.      GGGGeeeennnneeeerrrraaaattttiiiioooonnnn ooooffff aaaa HHHHAAAASSSSHHHH OOOOFFFF CCCCOOOOMMMMPPPPLLLLEEEEXXXX RRRREEEECCCCOOOORRRRDDDDSSSS
  966.  
  967.           # reading from file
  968.           # this is most easily done by having the file itself be
  969.           # in the raw data format as shown above.  perl is happy
  970.           # to parse complex data structures if declared as data, so
  971.           # sometimes it's easiest to do that
  972.  
  973.           # here's a piece by piece build up
  974.           $rec = {};
  975.           $rec->{series} = "flintstones";
  976.           $rec->{nights} = [ find_days() ];
  977.  
  978.  
  979.  
  980.  
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987.                                                                        PPPPaaaaggggeeee 11115555
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  995.  
  996.  
  997.  
  998.           @members = ();
  999.           # assume this file in field=value syntax
  1000.           while (<>) {
  1001.               %fields = split /[\s=]+/;
  1002.               push @members, { %fields };
  1003.           }
  1004.           $rec->{members} = [ @members ];
  1005.  
  1006.           # now remember the whole thing
  1007.           $TV{ $rec->{series} } = $rec;
  1008.  
  1009.           ###########################################################
  1010.           # now, you might want to make interesting extra fields that
  1011.           # include pointers back into the same data structure so if
  1012.           # change one piece, it changes everywhere, like for examples
  1013.           # if you wanted a {kids} field that was an array reference
  1014.           # to a list of the kids' records without having duplicate
  1015.           # records and thus update problems.
  1016.           ###########################################################
  1017.           foreach $family (keys %TV) {
  1018.               $rec = $TV{$family}; # temp pointer
  1019.               @kids = ();
  1020.               for $person ( @{ $rec->{members} } ) {
  1021.                   if ($person->{role} =~ /kid|son|daughter/) {
  1022.                       push @kids, $person;
  1023.                   }
  1024.               }
  1025.               # REMEMBER: $rec and $TV{$family} point to same data!!
  1026.               $rec->{kids} = [ @kids ];
  1027.           }
  1028.  
  1029.           # you copied the list, but the list itself contains pointers
  1030.           # to uncopied objects. this means that if you make bart get
  1031.           # older via
  1032.  
  1033.           $TV{simpsons}{kids}[0]{age}++;
  1034.  
  1035.           # then this would also change in
  1036.           print $TV{simpsons}{members}[2]{age};
  1037.  
  1038.           # because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2]
  1039.           # both point to the same underlying anonymous hash table
  1040.  
  1041.  
  1042.  
  1043.  
  1044.  
  1045.  
  1046.  
  1047.  
  1048.  
  1049.  
  1050.  
  1051.  
  1052.  
  1053.                                                                        PPPPaaaaggggeeee 11116666
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  1061.  
  1062.  
  1063.  
  1064.           # print the whole thing
  1065.           foreach $family ( keys %TV ) {
  1066.               print "the $family";
  1067.               print " is on during @{ $TV{$family}{nights} }\n";
  1068.               print "its members are:\n";
  1069.               for $who ( @{ $TV{$family}{members} } ) {
  1070.                   print " $who->{name} ($who->{role}), age $who->{age}\n";
  1071.               }
  1072.               print "it turns out that $TV{$family}{lead} has ";
  1073.               print scalar ( @{ $TV{$family}{kids} } ), " kids named ";
  1074.               print join (", ", map { $_->{name} } @{ $TV{$family}{kids} } );
  1075.               print "\n";
  1076.           }
  1077.  
  1078.  
  1079. DDDDaaaattttaaaabbbbaaaasssseeee TTTTiiiieeeessss
  1080.      You cannot easily tie a multilevel data structure (such as a hash of
  1081.      hashes) to a dbm file.  The first problem is that all but GDBM and
  1082.      Berkeley DB have size limitations, but beyond that, you also have
  1083.      problems with how references are to be represented on disk.  One
  1084.      experimental module that does partially attempt to address this need is
  1085.      the MLDBM module.  Check your nearest CPAN site as described in the
  1086.      _p_e_r_l_m_o_d_l_i_b manpage for source code to MLDBM.
  1087.  
  1088. SSSSEEEEEEEE AAAALLLLSSSSOOOO
  1089.      _p_e_r_l_r_e_f(1), _p_e_r_l_l_o_l(1), _p_e_r_l_d_a_t_a(1), _p_e_r_l_o_b_j(1)
  1090.  
  1091. AAAAUUUUTTTTHHHHOOOORRRR
  1092.      Tom Christiansen <_t_c_h_r_i_s_t@_p_e_r_l._c_o_m>
  1093.  
  1094.      Last update:  Wed Oct 23 04:57:50 MET DST 1996
  1095.  
  1096.  
  1097.  
  1098.  
  1099.  
  1100.  
  1101.  
  1102.  
  1103.  
  1104.  
  1105.  
  1106.  
  1107.  
  1108.  
  1109.  
  1110.  
  1111.  
  1112.  
  1113.  
  1114.  
  1115.  
  1116.  
  1117.  
  1118.  
  1119.                                                                        PPPPaaaaggggeeee 11117777
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))                                                          PPPPEEEERRRRLLLLDDDDSSSSCCCC((((1111))))
  1127.  
  1128.  
  1129.  
  1130.  
  1131.  
  1132.  
  1133.  
  1134.  
  1135.  
  1136.  
  1137.  
  1138.  
  1139.  
  1140.  
  1141.  
  1142.  
  1143.  
  1144.  
  1145.  
  1146.  
  1147.  
  1148.  
  1149.  
  1150.  
  1151.  
  1152.  
  1153.  
  1154.  
  1155.  
  1156.  
  1157.  
  1158.  
  1159.  
  1160.  
  1161.  
  1162.  
  1163.  
  1164.  
  1165.  
  1166.  
  1167.  
  1168.  
  1169.  
  1170.  
  1171.  
  1172.  
  1173.  
  1174.  
  1175.  
  1176.  
  1177.  
  1178.  
  1179.  
  1180.  
  1181.  
  1182.                                                                        PPPPaaaaggggeeee 11118888
  1183.  
  1184.  
  1185.  
  1186.  
  1187.  
  1188.  
  1189.